/*
 * 版权所有 (c) 华为技术有限公司 2022-2022
 */
package com.huawei.cameratest;

import android.app.Activity;
import android.content.Context;
import android.media.Image;
import android.media.ImageReader;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.util.Size;
import android.widget.TextView;

import java.io.File;
import java.nio.ByteBuffer;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;

class MyImageReader {
    private final String TAG = this.getClass().getSimpleName();
    private ImageReader imageReader;
    private ImageReader.OnImageAvailableListener mOnImageAvailableListener;
    private HandlerThread mBackgroundThread;
    private Handler mBackgroundHandler;
//    private TextView fpsTextView;
    private final int queueSize = 5;
    private ArrayBlockingQueue<byte[]> H264BufferQueue = new ArrayBlockingQueue<byte[]>(queueSize);
    private Size size;
    private int format;
    private File mFile;
    private int id;
    private int count;
    private int frameCount = 0;
    private long lastTime = new Date().getTime();
    private long currentTime;
    private double fps = 0.0;

    MyImageReader(Size size, int format, File mFile, int id) {
        this.size = size;
        this.format = format;
        this.mFile = mFile;
        this.id = id;
    }

    MyImageReader(Size size, int format, File mFile, int id, Activity context) {
        this.size = size;
        this.format = format;
        this.mFile = mFile;
        this.id = id;
        if (id == 0) {
//            fpsTextView = context.findViewById(R.id.text_passthrough_stream0_fps);
//            fpsTextView.setText("1000");
        } else {
//            fpsTextView = context.findViewById(R.id.text_passthrough_stream1_fps);
//            fpsTextView.setText("1000");
        }
    }

    public ImageReader run() {
        mBackgroundThread = new HandlerThread("CameraBackground" + id);
        mBackgroundThread.start();
        Log.i(TAG, "run: HandlerThread" + id + " start");
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());

        // YUV 420 888
        // YV12
        // NV21
        imageReader = ImageReader.newInstance(size.getWidth(), size.getHeight(), format, 2);
        mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader reader) {
//                if (count < 1) {
//                    Log.i(TAG, "shiyan:" + (new Date().getTime() - MultiImageReaderActivity.time));
//                }
//
                Image mImage = reader.acquireNextImage();
                try {
                    frameCount++;

                    if (frameCount >= 30) {
                        currentTime = new Date().getTime();
                        fps = frameCount * 1000.0 / (currentTime - lastTime);
                        lastTime = currentTime;
                        frameCount = 0;
                        Log.e(TAG, "passthrough stream " + id + " fps: " + fps);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                count++;
                ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                if (H264BufferQueue.size() >= queueSize) {
                    Log.e(TAG,  "queue size is over");
                    H264BufferQueue.poll();
                }
                H264BufferQueue.add(bytes);
                mImage.close();
            }
        };
        imageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
        return imageReader;
    }

    public double getFps() {
        return fps;
    }

    public void close() {
        mBackgroundThread.quitSafely();
        Log.d(TAG, "stopBackgroundThread: handlerThread" + id + " quitSafely");
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            Log.d(TAG, "stopBackgroundThread: handlerThread" + id + " stop");
            mBackgroundHandler = null;
            Log.d(TAG, "stopBackgroundThread: handler" + id + " stop");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public ArrayBlockingQueue<byte[]> getH264BufferQueue() {
        return H264BufferQueue;
    }

    public int getCount() {
        return count;
    }

}
